package com.dp;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

import org.apache.hadoop.hive.ql.parse.ASTNode;
import org.apache.hadoop.hive.ql.parse.AbstractSemanticAnalyzerHook;
import org.apache.hadoop.hive.ql.parse.HiveParser;
import org.apache.hadoop.hive.ql.parse.HiveSemanticAnalyzerHookContext;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.session.SessionState;

public class SuperHiveUser
    extends AbstractSemanticAnalyzerHook {

  private static String admin = "hadoop";

  static {
    String hiveHome = System.getenv("HIVE_HOME");
    Properties properties = new Properties();
    try {
      File file = new File(hiveHome + "/conf/hive.properties");
      if (file.exists()) {
        properties.load(new FileReader(file));
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    admin = properties.getProperty("hive.auth.grantor", admin);
  }

  /**
   * control privilege.
   */
  public ASTNode preAnalyze(HiveSemanticAnalyzerHookContext context, ASTNode ast)
      throws SemanticException {
    switch (ast.getToken().getType()) {
      case HiveParser.TOK_CREATEDATABASE:
      case HiveParser.TOK_CREATEROLE:
      case HiveParser.TOK_DROPDATABASE:
      case HiveParser.TOK_DROPROLE:
      case HiveParser.TOK_GRANT:
      case HiveParser.TOK_GRANT_ROLE:
      case HiveParser.TOK_REVOKE:
      case HiveParser.TOK_REVOKE_ROLE:
      case HiveParser.TOK_SHOWDATABASES:
      case HiveParser.TOK_SHOWTABLES:
        String userName = null;
        if ((SessionState.get() != null) && (SessionState.get().getAuthenticator() != null)) {
          userName = SessionState.get().getAuthenticator().getUserName();
        }
        if (!admin.equalsIgnoreCase(userName)) {
          throw new SemanticException("version2: " + userName + " can't use ADMIN options");
        }
        break;
      default:
        break;
    }
    return ast;
  }
}

